﻿#pragma execution_character_set("utf-8")
// 本文件为utf-8 编码格式

#include "GDHttpUtil.h"
#include "../GdDefine.h"
#include "GDUtil.h"
#include "../CartoonHouse.h"

static int viewCount = 0;

GDHttpUtil::GDHttpUtil(void)
:pTarget(NULL)
{
    if(IS_DEBUG) CCLog("GDHttpUtil = %d\n", ++viewCount);
	if (IS_DEBUG){
		debugUrl = "&XDEBUG_SESSION_START=ECLIPSE_DBGP&KEY=14356352667443";
	}
}


GDHttpUtil::~GDHttpUtil(void)
{
	if (IS_DEBUG) CCLog("~GDHttpUtil = %d\n", --viewCount);
	pTarget = NULL;
}

static GDHttpUtil* instance=NULL;

GDHttpUtil* GDHttpUtil::getInstance()
{
	GDHttpUtil *obj = new GDHttpUtil();
	obj->retain();
	obj->autorelease();
	return obj;

	/*
	if (instance == NULL){
		instance = new GDHttpUtil();
	}
	return instance;
	*/
}

std::string GDHttpUtil::processUrl(std::string url){
	std::string getRul = url + debugUrl + ___GD_ORIGIN___;

	string token = "";
	if (!token.empty()){
		getRul += "&gd_token=" + token;
	}

	return getRul;
}

void GDHttpUtil::send_get(const std::string& url,
	std::map<std::string, std::string> key_value,
	CAObject* pTarget,
	SEL_CommonHttpJson pSelector,
	bool isLoading)
{
	this->pTarget = pTarget;
	this->pSelector = pSelector;
	std::string getRul = processUrl(url);
    if (IS_DEBUG)  CCLog("GET请求地址：%s", getRul.c_str());
	CommonHttpManager::getInstance()->send_get(getRul, key_value, this, CommonHttpJson_selector(GDHttpUtil::onHttpRequestFinished), isLoading);
}

void GDHttpUtil::send_post(const std::string& url,
	std::map<std::string, std::string> key_value,
	CAObject* pTarget,
	SEL_CommonHttpJson pSelector,
	bool isLoading)
{
	this->pTarget = pTarget;
	this->pSelector = pSelector;
	std::string getRul = processUrl(url);
	if (IS_DEBUG) CCLog("POST请求地址：%s", getRul.c_str());
	CommonHttpManager::getInstance()->send_post(getRul, key_value, this, CommonHttpJson_selector(GDHttpUtil::onHttpRequestFinished), isLoading);
}

void GDHttpUtil::send_postFile(const std::string& url,
	std::map<std::string, std::string> key_value,
	const std::string& file,
	CAObject* pTarget,
	SEL_CommonHttpJson pSelector,
	bool isLoading)
{
	this->pTarget = pTarget;
	this->pSelector = pSelector;
	std::string getRul = processUrl(url);
	if (IS_DEBUG) CCLog("POSTFILE请求地址：%s", getRul.c_str());
	CommonHttpManager::getInstance()->send_postFile(getRul, key_value, file, this, CommonHttpJson_selector(GDHttpUtil::onHttpRequestFinished), isLoading);
}

void GDHttpUtil::onHttpRequestFinished(const HttpResponseStatus& status, const CSJson::Value& json)
{
	this->release();
	
	if (GD_HTTP_RESPONSE_OK) // 成功
	{
		//if (IS_DEBUG) CCLog("网络请求返回数据：%s", json.toStyledString().c_str());
		// 统一更新用户数据
		
	}
	else
	{
		if (pTarget){
			(pTarget->*pSelector)(status, json);
		}
	}
}

void GDHttpUtil::onH5LoginFinished(const HttpResponseStatus& status, const CSJson::Value& json)
{
	if (GD_HTTP_RESPONSE_OK) // 登陆成功
	{
		if (IS_DEBUG) CCLog("h5登陆成功");
		//GdUserModule::getInstance()->setLoginOkData(json);
	}
}